package com.jiepos.mpos.core.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.jiepos.mpos.biz.outservice.service.ServiceInterLogService;
import com.jiepos.mpos.biz.user.service.AppInsInfService;
import com.jiepos.mpos.common.constant.ExceptionConstant;
import com.jiepos.mpos.common.entity.App_Ins_InfEntity;
import com.jiepos.mpos.common.entity.App_Service_Inter_LogEntity;
import com.jiepos.mpos.core.exception.MposException;
import com.jiepos.mpos.core.util.StringUtils;
import com.jiepos.mpos.inter.intopieces.dto.RequestDTO;
import com.jiepos.mpos.inter.intopieces.dto.ResponseDTO;
import com.jiepos.mpos.inter.intopieces.utils.FinalDataUtils;
import com.jiepos.mpos.inter.intopieces.utils.SignatureUtil;

@Component
public class BaseInterService {

	private static final String DES_KEY = "1E4A1B03D1B6CD8A174A826F76E009F4";
	private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJN2m4vRe9yb6LYRiGcXQTj5cmvXDehkSkGjULTT3YUOHAJRacFHEOb7A2VsMBwEB+/TK56DSiER/1mQmnj0YW6C9A5Zh/7dHG6cRXr6+KQGPKdMvDTrtj3tChCoZj6+PH9w2cuGSUaJNKtkiwK+/STY2nrC3GOOrkkr5xUHZx+QIDAQAB";
	private static final String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIk3abi9F73JvothGIZxdBOPlya9cN6GRKQaNQtNPdhQ4cAlFpwUcQ5vsDZWwwHAQH79MrnoNKIRH/WZCaePRhboL0DlmH/t0cbpxFevr4pAY8p0y8NOu2Pe0KEKhmPr48f3DZy4ZJRok0q2SLAr79JNjaesLcY46uSSvnFQdnH5AgMBAAECgYBTkApzNbzKmJzQtr2/ykHdU7nCHuYore4JXehlzJFYNdF1OWDuhkhfeUb/oJC7dUAR1dJZgv7in7kt0RgfEdKlZkZSjf9maA+eg+Sy6+QHneK1tsbsFntaAykaInpFBDZq0dHstOoQMQSNJtyEfCIz97E9l1XW8R+pN4G4S75pLQJBAL9rKp+hSCZJi+QzaYZbAgFjs4k6XkVwwnjr3eVz3lttJ+CwoLnv05CVsSrt4apZ6+q+a0n8yJbc6HNnOZxLNocCQQC3gs27dMmZOI/FLaUeTEe7XVR36h/JBIg5omedqHcKD/b3ltTPak9oI+RTYSXttN4N9CrczCMraZJyO5RrSrN/AkEAtuhRR02Worc+TCVwXSjTRr6dTLCQaiwwN9myI9HPFG++Xi6ItoNbFtpi+5FpRB0+mAWygXVhuv6Fw9hMLXOVOwJANcGtfqJBhA7bnsk2O1/hC3PVkKMW2I3pUejPLZHx/RKcJ/8ZLAFabYlGE167+5wmCDRkcfWiv87XRXtKiPuDBQJBAI7ShgI5727Kzttg5JUsfVLGWZFz8olrPiXp9JqV1HcZrNpemHjMF+G3YTAojyYzFBd5KDGqMnn1B2kXcZ09kG0=";
	
	@Autowired
	private ServiceInterLogService serviceInterLogService;
	@Autowired
	private AppInsInfService insInfService;
	
	/**
	 * 解密请求报文与验签
	 * @param requestDto
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> getRequestBizContent(RequestDTO requestDto) throws Exception{
		if(requestDto == null){
			throw new MposException(ExceptionConstant.MER_REQ_NULL);
		}
		/*验证机构信息*/
		if(StringUtils.isBlank(requestDto.getInstCode())){
			throw new MposException(ExceptionConstant.MER_REQ_INS_NULL);
		}
		/*解密机构号*/
		String instUuid = SignatureUtil.decrypt3DES(DES_KEY, requestDto.getInstCode());
		if(StringUtils.isBlank(instUuid)){
			throw new MposException(ExceptionConstant.MER_REQ_INS_NOT_EXISTS);
		}
		/*查询是否存在对应机构*/
		App_Ins_InfEntity inf = insInfService.getInsInfByUuid(instUuid);
		if(inf == null || StringUtils.isBlank(inf.getIns_uuid())){
			throw new MposException(ExceptionConstant.MER_REQ_INS_NOT_EXISTS);
		}
		/*提取加密的请求业务报文*/
		String bizContent = requestDto.getBizContent();
		/*无业务请求报文*/
		if(StringUtils.isBlank(bizContent)){
			throw new MposException(ExceptionConstant.MER_BIZ_DATA_NULL);
		}
		/*解密报文*/
		Map<String, String> data = SignatureUtil.decryptToMapByPublicKey(bizContent, publicKey);
		if(data == null || data.isEmpty()){
			throw new MposException(ExceptionConstant.MER_BIZ_DATA_ERROR);
		}
		/*获取签名*/
		String signature = data.get(FinalDataUtils.SIGNATURE);
		if(StringUtils.isNotBlank(signature)){
			data.remove(FinalDataUtils.SIGNATURE);
			/*验签*/
			if(!signature.equals(SignatureUtil.encrypt3DES(DES_KEY, SignatureUtil.MD5Encode(data)))){
				throw new MposException(ExceptionConstant.MER_SIGN_ERROR);
			}
		}
		/*解密机构标识*/
		data.put(FinalDataUtils.INS_UUID, instUuid); // 机构标识
		return data;
	}
	
	/**
	 * 加密应答报文
	 * @param reqBizContent
	 * @param resBizContent
	 * @return
	 * @throws Exception
	 */
	public String getResponseBizContent(Map<String, String> reqBizContent, Map<String, String> resBizContent) throws Exception{
		if(resBizContent == null || resBizContent.isEmpty()){
			return null;
		}
		/*应答参数签名*/
		String signature = SignatureUtil.encrypt3DES(DES_KEY, SignatureUtil.MD5Encode(resBizContent));
		resBizContent.put(FinalDataUtils.SIGNATURE, signature);
		/*应答参数加密*/
		return SignatureUtil.encryptByPrivateKey(resBizContent, privateKey);
	}
	
	/**
	 * 保存请求应答日志
	 * @param requestDto 请求对象实体
	 * @param responseDto 应答对象实体
	 * @param reqBizContent 解密后的请求业务报文
	 * @param resBizContent 加密前的应答业务报文
	 * @param interType 服务名
	 */
	@Async
	public void saveLog(RequestDTO requestDto, ResponseDTO responseDto, Map<String, String> reqBizContent, Map<String, String> resBizContent, String interType){
		App_Service_Inter_LogEntity logEntity = new App_Service_Inter_LogEntity();
		logEntity.setInter_type(interType);
		if(requestDto != null){
			logEntity.setInter_version(requestDto.getVersion());
			logEntity.setReq_content(requestDto.toString());
			logEntity.setReq_sn_no(requestDto.getRequestId());
		}
		if(reqBizContent != null){
			logEntity.setIns_uuid(reqBizContent.get(FinalDataUtils.INS_UUID));
			reqBizContent.remove(FinalDataUtils.INS_UUID);
			logEntity.setReq_biz_content(reqBizContent.toString());
			logEntity.setMchnt_cd(reqBizContent.get(FinalDataUtils.MCHNT_CD));// 商户号
			logEntity.setService_mchnt_cd(reqBizContent.get(FinalDataUtils.OUT_MCHNT_CD));// 外部商户号
		}
		logEntity.setRes_biz_content(resBizContent != null ? resBizContent.toString() : "");
		logEntity.setRes_content(responseDto.toString());
		logEntity.setRsp_code(responseDto.getRsp_code());
		logEntity.setRsp_msg(responseDto.getRsp_msg());
		
		serviceInterLogService.save(logEntity);
	}
}
